package com.js.common.controller;

import com.js.common.response.ObjectRestResponse;
import com.js.common.response.TableResultResponse;
import com.js.common.service.BaseService;
import com.js.common.util.Query;
import com.js.core.context.BaseContextHandler;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author ygl
 * @create 2018-11-01
 * @DESCRIPTION
 * 用于单表操作的基类控制器
 * @param <Entity> 实体
 * @param <PK> 主键类型
 */
public class BaseController<Entity,PK> {

    @Autowired
    protected BaseService<Entity> baseService;

    @ApiOperation("新增单个对象")
    @PostMapping("")
    public ObjectRestResponse<Entity> add(@RequestBody Entity entity){
        baseService.insertSelective(entity);
        return new ObjectRestResponse<Entity>().data(entity);
    }

    @ApiOperation("查询单个对象")
    @GetMapping("/{id}")
    public ObjectRestResponse<Entity> get(@PathVariable PK id){
        ObjectRestResponse<Entity> entityObjectRestResponse = new ObjectRestResponse<>();
        Object o = baseService.selectById(id);
        entityObjectRestResponse.data((Entity)o);
        return entityObjectRestResponse;
    }

    @ApiOperation("更新单个对象")
    @PutMapping("/{id}")
    public ObjectRestResponse<Entity> update(@RequestBody Entity entity){
        baseService.updateSelectiveById(entity);
        return new ObjectRestResponse<Entity>().data(entity);
    }

    @ApiOperation("移除单个对象")
    @DeleteMapping("/{id}")
    public ObjectRestResponse<Entity> remove(@PathVariable PK id){
        baseService.deleteById(id);
        return new ObjectRestResponse<Entity>();
    }

    @ApiOperation("获取所有数据")
    @GetMapping("/all")
    public List<Entity> all(){
        return baseService.selectAll();
    }

    @ApiOperation("分页获取数据")
    @RequestMapping(value = "/page",method = RequestMethod.GET)
    @ResponseBody
    public TableResultResponse<Entity> list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        return baseService.selectByQuery(query);
    }

    public String getCurrentUserName(){
        return BaseContextHandler.getUsername();
    }
}
